package com.chhuang.utils.file;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.chhuang.utils.string.StringUtil;
/**
 * 
 * @author 黄晨
 *
 */
public class ByteFileUtil {
	
	/**
	 * 将文件按照二进制读取，返回字节数组
	 * @param fileName
	 * @return
	 * @throws IOException 
	 */
	public static byte[] readFileByBytes(String fileName) throws IOException {
		if(StringUtil.isEmpty(fileName) || !new File(fileName).exists()) {
			throw new IOException("文件不存在");
		}
		
		InputStream in = null;
		ByteArrayOutputStream out = null;
		
		byte[] filebyte = null;
		
		try {
			byte[] tempbytes = new byte[1024];
			int byteread = 0;
			in = new FileInputStream(fileName);
			int fileSize = showAvailableBytes(in);
			
			if(fileSize == 0) {
				throw new IOException("文件内容无效。");
			}
			
			out = new ByteArrayOutputStream(1024);
			// 读入多个字节到字节数组中，byteread为一次读入的字节数
			while ((byteread = in.read(tempbytes)) != -1) {
				out.write(tempbytes, 0, byteread);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			
			try {
				if (in != null) {
					in.close();
				}
				if(out != null) {
					out.close();
				}
			} catch (IOException e1) {
			}
		}
		
		filebyte = out.toByteArray();
		
		return filebyte;
	}
	
	/**
	 * 显示输入流中还剩的字节数
	 */
	private static int showAvailableBytes(InputStream in) {
		try {
			return in.available();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return 0;
	}
	
    /**
     * 将字节数组写入文件
     * @param path
     * @param bytes
     * @throws IOException
     */
	public static void writeBytesToFile(String path, byte[] bytes) throws IOException {
		if(StringUtil.isEmpty(path) || bytes == null || bytes.length == 0) {
			throw new IOException("不能写入空字节，或传入文件名为空");
		}
		
		File file = new File(path);
		
		if(!file.exists()) {
			file.createNewFile();
		}
		
		FileOutputStream fos = new FileOutputStream(path);

		fos.write(bytes);
		fos.close();
	}
	
	/**
	 * 把字节写入文件
	 * @param fileBytes
	 * @param filePath
	 */
	public static void writeFile(byte[] fileBytes, String filePath){
		writeFile(fileBytes, false, filePath);
	}
	
	/**
	 * 把字节追加写入文件
	 * @param fileBytes
	 * @param filePath
	 */
	public static void writeFile(byte[] fileBytes,boolean isAppend, String filePath){
		File outputFile = new File(filePath); 
		FileOutputStream outputFileStream = null;
		try {
			outputFileStream = new FileOutputStream(outputFile,isAppend);
			outputFileStream.write(fileBytes);
		} catch (FileNotFoundException e) {  
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
